﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

//using OpenPop.Mime;
//using OpenPop.Pop3;
//using OpenPop.Pop3.Exceptions; 
namespace XKPlatform.Common
{
    public class EmailHelper
    {
        private static readonly string accout = "nestleassistantpbiservice@xspeedtech.cn"; //邮箱账户
        private static readonly string pass = "Nestle123";//邮箱密码
        private static readonly string popServer = "pop.exmail.qq.com"; //pop服务地址
        private static readonly int popPort = 110; //pop服务端口号（110）
        private static readonly bool isUseSSL = false;



        //#region 验证邮箱是否登录成功
        //public static bool ValidateAccount(ref string error)
        //{
        //    Pop3Client client = new Pop3Client();
        //    try
        //    {
        //        client.Connect(popServer, popPort, isUseSSL);
        //        client.Authenticate(accout, pass);
        //    }
        //    catch (InvalidLoginException ex)
        //    {
        //        error = "邮箱登录失败！";
        //        return false;
        //    }
        //    catch (InvalidUseException ex)
        //    {
        //        error = "邮箱登录失败！";
        //        return false;
        //    }
        //    catch (PopServerNotFoundException ex)
        //    {
        //        error = "服务器没有找到！";
        //        return false;
        //    }
        //    catch (PopServerException ex)
        //    {
        //        error = "请在邮箱开通POP3/SMTP！";
        //        return false;
        //    }
        //    catch (Exception ex)
        //    {
        //        error = "连接出现异常";
        //        return false;
        //    }
        //    finally
        //    {
        //        //client.Disconnect();
        //    }
        //    return true;
        //}
        //#endregion

        //#region 下载邮件附件
        ///// <summary>
        ///// 批量下载邮件附件
        ///// </summary>
        ///// <param name="path">附件保存目录</param>
        ///// <param name="sentTime">邮件接收时间截止时间</param>
        //public static IList<EmailContentModel> DownAttachments(string path, DateTime? sentTime = null)
        //{
        //    using (Pop3Client client = new Pop3Client())
        //    {
        //        if (client.Connected)
        //        {
        //            client.Disconnect();
        //        }
        //        client.Connect(popServer, popPort, isUseSSL);
        //        client.Authenticate(accout, pass, AuthenticationMethod.UsernameAndPassword);
        //        int messageCount = client.GetMessageCount();
        //        IList<EmailContentModel> list = new List<EmailContentModel>();
        //        for (int i = 1; i <= messageCount; i++)
        //        {
        //            Message message = client.GetMessage(i);
        //            string from = message.Headers.From.Address;
        //            string subject = message.Headers.Subject;
        //            DateTime Datesent = message.Headers.DateSent;
        //            string messageId = message.Headers.MessageId;
        //            EmailContentModel emailContentModel = new EmailContentModel
        //            {
        //                From = from,
        //                Subject = subject,
        //                Datesent = Datesent,
        //                MessageId = messageId,
        //                EmailAttachments = new List<EmailAttachment>()
        //            };
        //            // 如果传递下载截止时间，则跳过该时间之前的
        //            if (sentTime != null && Datesent < sentTime)
        //            {
        //                continue;
        //            }

        //            List<MessagePart> messageParts = message.FindAllAttachments();
        //            foreach (var item in messageParts)
        //            {
        //                if (!item.IsAttachment)
        //                {
        //                    continue;
        //                }

        //                string filePath = Path.Combine(path, item.FileName);
        //                if (File.Exists(path + item.FileName))
        //                {
        //                    continue;
        //                }

        //                if (item.FileName.Contains(".xls") || item.FileName.Contains(".xlsx") || item.FileName.Contains(".csv"))
        //                {
        //                    EmailAttachment emailAttachment = new EmailAttachment
        //                    {
        //                        FileName = item.FileName,
        //                        FilePath = filePath
        //                    };
        //                    File.WriteAllBytes(filePath, item.Body);
        //                    emailContentModel.EmailAttachments.Add(emailAttachment);
        //                }
        //            }

        //            list.Add(emailContentModel);
        //        }

        //        return list;
        //    }
        //}


        ///// <summary>
        ///// 下载邮件附件
        ///// </summary>
        //public static void DownAttachmentsById(string path, int messageId)
        //{
        //    using (Pop3Client client = new Pop3Client())
        //    {
        //        if (client.Connected)
        //        {
        //            client.Disconnect();
        //        }
        //        client.Connect(popServer, popPort, isUseSSL);
        //        client.Authenticate(accout, pass, AuthenticationMethod.UsernameAndPassword);
        //        Message message = client.GetMessage(messageId);
        //        string senders = message.Headers.From.DisplayName;
        //        string from = message.Headers.From.Address;
        //        string subject = message.Headers.Subject;
        //        DateTime Datesent = message.Headers.DateSent;


        //        List<MessagePart> messageParts = message.FindAllAttachments();
        //        foreach (var item in messageParts)
        //        {
        //            if (item.IsAttachment)
        //            {
        //                if (!File.Exists(path + item.FileName))
        //                {
        //                    if (item.FileName.Contains(".xls") || item.FileName.Contains(".xlsx") || item.FileName.Contains(".csv"))
        //                        File.WriteAllBytes(path + item.FileName, item.Body);
        //                }
        //            }
        //        }

        //        //MessagePart nomessageParts = message.FindFirstHtmlVersion();
        //        //string html = nomessageParts.GetBodyAsText();
        //        //Regex reg = new Regex(@"(?is)<a[^>]*?href=(['""]?)(?<url>[^'""\s>]+)\1[^>]*>(?<text>(?:(?!</?a\b).)*)</a>");
        //        //MatchCollection mc = reg.Matches(html);
        //        //string url = string.Empty;

        //        //url = mc[0].Groups["url"].Value;
        //        //HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
        //        //req.Method = "GET";
        //        //using (WebResponse res = req.GetResponse())
        //        //{
        //        //    string reader = new StreamReader(res.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
        //        //    MatchCollection ms = reg.Matches(reader);
        //        //    url = ms[0].Groups["url"].Value;
        //        //}
        //    }
        //}
        //#endregion


        //#region
        ///// <summary>
        ///// 获取邮件数量
        ///// </summary>
        ///// <returns></returns>
        //public static int GetEmailCount()
        //{
        //    int messageCount = 0;
        //    using (Pop3Client client = new Pop3Client())
        //    {
        //        if (client.Connected)
        //        {
        //            client.Disconnect();
        //        }
        //        client.Connect(popServer, popPort, isUseSSL);
        //        client.Authenticate(accout, pass, AuthenticationMethod.UsernameAndPassword);
        //        messageCount = client.GetMessageCount();
        //    }

        //    return messageCount;
        //}
        //#endregion


    }
}
